/****************************************************
          File Name:pisces_readconf.c
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Tue 13 Jan 2015 10:18:46 AM CST
*****************************************************/

#include "pisces_readconf.h"
#include "header.h"

static int getinfo(const char *conf, char *res)
{
    int i;
    unsigned long j, len;
    char *line[] = {
        "HOSTNAME", "PORT", "ROOT_DIR",
        "CGI_BIN", "BACK_LOG"
    };

    for (i = 0; i < CONF_NUM; i++) {
        if (strstr(conf, line[i])) {
            len = strlen(line[i]) + 1;
            memset(res, 0, 256);
            for (j = 0; j < strlen(conf) - len; j++)
                res[j] = conf[len + j];
            break;
        }
    }
    return i;
}

void parse_file(const char *buf, pisces_ctx_t * ctx)
{
    int i = 0;
    int index;
    char tmp[256];
    char res[256];

    while (buf[i] != '\0') {
 again:
        if (buf[i] == '#' || buf[i] == '\n')
            for (; buf[i] != '\n'; i++) ;
        if (buf[i + 1] == '#' || buf[i] == '\n') {
            i += 1;
            goto again;
        }
        index = 0;
        memset(tmp, 0, 256);
        for (; buf[i] != '\n' && buf[i] != '\0'; i++, index++)
            tmp[index] = buf[i];

        switch (getinfo(tmp, res)) {
        case -1:
            break;
        case 0:
            ctx->conf->host = (char *)malloc(strlen(res) + 1);
            strcpy(ctx->conf->host, res);
            break;
        case 1:
            ctx->conf->port = (char *)malloc(strlen(res) + 1);
            strcpy(ctx->conf->port, res);
            break;
        case 2:
            ctx->conf->root_dir = (char *)malloc(strlen(res) + 1);
            strcpy(ctx->conf->root_dir, res);
            break;
        case 3:
            ctx->conf->cgi_dir = (char *)malloc(strlen(res) + 1);
            strcpy(ctx->conf->cgi_dir, res);
            break;
        case 4:
            ctx->conf->backlog = atoi(res);
            break;
        }
    }
}

int pisces_readconf(pisces_ctx_t * ctx)
{
    int fd = 0;
    struct stat file;
    ctx->conf = (pisces_conf_t *) malloc(sizeof(pisces_conf_t));
    if ((fd = open(CONF_FILE_PATH, O_RDONLY)) != -1) {
        fstat(fd, &file);
        char *buf = (char *)malloc(file.st_size);
        read(fd, buf, file.st_size);
        parse_file(buf, ctx);
        free(buf);
        return 0;
    }
    return -1;
}
